<!--
 * @Description: 群详情
 * @Author: Kerwin
 * @Date: 2023-07-25 10:21:35
 * @LastEditTime: 2025-04-11 16:34:37
 * @LastEditors:  Please set LastEditors
-->

<template>
  <view class="container">
    <hy-nav-bar :title="configStore.hideData ? '信息设置' : `群聊信息（${userList?.length ?? ''}）`"> </hy-nav-bar>
    <view class="userList mb2">
      <view class="user" v-for="user in userList" :key="user.rongId">
        <!-- <u-image :src="getImgFullPath(user.avatar)" mode="widthFix" width="90rpx" height="90rpx"
          :error-icon="RY_AVATAR"></u-image> -->
        <u-avatar :src="getImgFullPath(user.avatar) ? getImgFullPath(user.avatar) : RY_AVATAR"></u-avatar>
        <view class="name">
          {{ user.circle_nickname || user.nickname }}
        </view>
      </view>
      <view class="user" v-if="!configStore.hideData">
        <u-icon custom-prefix="custom-icon" name="tianjia" size="95" color="#666" @click="addNew"
          v-if="editPermission"></u-icon>
        <view class="name"></view>
      </view>
    </view>
    <u-cell-group :title-style="{
      color: '#000'
    }">

      <van-cell v-if="!configStore.hideData" size="large" title="群二维码" is-link @click="editGroupQr">
        <template #value>
          <van-icon name="qr" size="large" />
        </template>
      </van-cell>


      <u-cell-item :title="configStore.hideData ? '名称' : '群聊名称'" :value="groupInfo.name"
        @click="editGroupName"></u-cell-item>
      <u-cell-item :title="configStore.hideData ? '名称' : '群简介'" :value="groupInfo.remark"
        @click="editGroupRemark"></u-cell-item>
      <!-- <u-cell-item :title="configStore.hideData ? '昵称' : '我在群里的昵称'"
        :value="mySelfInfoInGroup.circle_nickname || mySelfInfoInGroup.nickname" @click="editNickname"></u-cell-item> -->
    </u-cell-group>
 
    <u-button  v-if="groupInfo.userId != userId"  class="footer" @click="show = true" type="error" :ripple="true" ripple-bg-color="#fa3534"
      plain>删除并退出群聊</u-button>
    <u-popup v-model="show" mode="bottom" height="25%">
      <view>
        <view class="text">退出后不会通知群主，且不会再接收此聊天群消息，确定退出群聊？</view>
        <view class="footerItem">
          <u-button class="btns" @click="deleteGroup" :ripple="true" ripple-bg-color="#fef0f0" plain>确定</u-button>
          <u-button class="btns" @click="show = false" :ripple="true" ripple-bg-color="#fef0f0" plain>取消</u-button>

        </view>
      </view>

    </u-popup>

  </view>
</template>


<script setup lang="ts">
import { reactive, ref, computed, onBeforeMount, watch } from 'vue'
import {
  onLoad,
  onShow,
  onReady,
  onReachBottom,
  onShareAppMessage
} from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { socialApi } from '@/api'
import { getImgFullPath } from '@/utils/index'
import { route } from '@/utils/common'
import { UPLOADURL, RY_AVATAR } from '@/common/config'
import { useUserStore, useConfigStore, useChatStore } from '@/store'
import { sharePathFormat } from '@/common/wechat-share'
import RongIMLib from '@/packageD/common/rongCloud/im_init';
const ryStore = useChatStore()
const userStore = useUserStore()
// const { userInfo } = storeToRefs(userStore)
const configStore = useConfigStore()
const groupInfo = ref({
  gid: '',
  cid: '',
  id: 0,
  userId:0
})
const userList = ref([])
const userId = userStore.userInfo.id  
const show = ref(false)
const mySelfInfoInGroup = computed(() => {
  const user = userList.value.find((item: any) => item.id == userStore.userInfo.id)
  return user || userStore.userInfo
})
async function circleUserList() {
  const { data } = await socialApi.circleUserList({
    chatGroupId: groupInfo.value.gid,
    friendCircleId: groupInfo.value.cid,
    detail: true,
    // pageSize: 19
    noPaging: true
  })
  console.log(data, 'qunxiaox');

  if (data && data.records.length > 0) {
    userList.value = data.records.map(
      (e: { userDetail: { avatar: string }; nickname: any; id: any }) => {

        if (!e.userDetail.avatar) {
          e.userDetail.avatar = RY_AVATAR
        }
        return { ...e.userDetail, circle_nickname: e.nickname, fid: e.id }
      }
    )
  } else {
    userList.value = []
  }
}
async function getCircleInfo() {
  const { data } = await socialApi.circleInfo({
    id: groupInfo.value.cid
    // detail: true
  })
  console.log('当前群信息：', data);

  groupInfo.value = { ...groupInfo.value, ...data }
}

const editPermission = computed(() => {
  return groupInfo.value.userId === userStore.userInfo.id
})
function hasPermission() {
  if (!editPermission.value) {
    uni.showModal({
      title: '',
      content: '当前群聊仅群主/管理员可修改',
      showCancel: true,
      success: ({ confirm, cancel }) => { }
    })
  }
  return editPermission.value
}
function editGroupQr() {
  jumpFn(5)
}
function editGroupName() {
  console.log(1);

  if (!hasPermission()) return
  jumpFn(2)
}
function editGroupRemark() {
  if (!hasPermission()) return
  jumpFn(3)
}
function editNickname() {
  jumpFn(1)
}
function jumpFn(type: any) {
  console.log(333);

  route({
    url: '/packageD/pages/chatGroup/infoEdit',
    params: {
      type,
      groupInfo: JSON.stringify(groupInfo.value),
      avatarList: JSON.stringify(
        userList.value.slice(0, 9).map((item) => item.avatar)
      )
    }
  })
  uni.setStorageSync('mySelfInfoInGroup', JSON.stringify(mySelfInfoInGroup.value))
}
function addNew() {
  route({
    url: '/packageA/pages/chatGroup/addNewcomer',
    params: {
      cid: groupInfo.value.cid,
      gid: groupInfo.value.gid
    }
  })
}

// 删除会话列表聊天
async function toDel(item: { targetId: string; conversationType: RongIMLib.ConversationType;uState:boolean }) {
  ryStore.removeConversation(item.targetId, item.conversationType,item.uState)
}
const deleteGroup = async () => {
  console.log('退群', groupInfo.value.id, userStore.userInfo.id);
  const { code } = await socialApi.leaveChatGroupCity({
    userId: userStore.userInfo.id,
    friendCircleId: groupInfo.value.id,
  })
  console.log(code, '退群');
  if (code == 200) {
    toDel({
      targetId: groupInfo.value.cid,
      conversationType: RongIMLib.ConversationType.GROUP,
      uState:false
    })
    uni.redirectTo({
      url: '/packageD/pages/index/index?tab=0&isShop=false'
    });
  }
}


//当前用户在群信息
const userInfoFormChat = async () => {
  const { data } = await socialApi.userInfoFormChat({
    friendCircleId: groupInfo.value.id,
  })

  console.log(
    data, '用户在群的信息'
  );



}



onLoad(async (option) => {
  groupInfo.value.gid = option?.gid
  groupInfo.value.cid = option?.cid
})
onShow(async () => {
  await circleUserList()
  await getCircleInfo()
  await userInfoFormChat()
})
onShareAppMessage(() => {
  return {
    title: `邀请你加入${groupInfo.value.name}群聊`,
    desc: groupInfo.value.remark ?? '',
    imageUrl: getImgFullPath(groupInfo.value.avatar),
    path: sharePathFormat({ redirect_url: '/pages/index/index' })
  }
})
</script>

<style lang="scss" scoped>
@import '@/styles/helper.scss';

.container {
  padding: 30rpx 0;

  .userList {
    background: #fff;
    padding: 30rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    gap: 20rpx;

    .user {
      width: calc((100% - 80rpx) / 5);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      position: relative;

      .name {
        width: 90rpx;
        font-size: 22rpx;
        word-break: break-all;
        text-align: center;
        margin-top: 10rpx;
        color: #666;
        @include ellipsis();
      }

      .btn {
        background-color: transparent;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;

        &::after {
          border: none;
        }
      }
    }
  }
}

.footer {
  margin: 40rpx 0;
}

.text {
  font-size: 24rpx;
  color: #666;
  padding:15rpx;
}

.footerItem {
  margin: 30rpx 0;

  //  background-color: green;

  :deep(.u-btn) {
    border: 1rpx solid transparent !important;
  }
.btns{
  height: 100rpx;
  margin: auto;
  margin-bottom: 30rpx;
}


}
</style>
